<template>
   <view class="search-box" :style="{top: statusBarHeight + 'px'}">
      <view class="search-container">
        <view class="search-input">
          <uni-icons type="search" color="#999" size="20"></uni-icons>
          <input 
            type="text" 
            v-model="searchKeyword" 
            placeholder="搜索科室" 
            @confirm="handleSearch"
            @input="handleInputChange"
            :focus="isSearching"
          />
        </view>
        <text 
          v-if="isSearching" 
          class="cancel-btn"
          @click="cancelSearch"
        >取消</text>
      </view>
      </view>
    
    <!-- 科室列表 -->
    <scroll-view 
     class="department-list" 
           scroll-y 
           :style="{top: statusBarHeight + 50 + 'px'}"
    >
      <view class="result-list">
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-state">
          <view class="loading-icon"></view>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 科室列表 -->
        <view 
          v-for="(dept, index) in filteredDepartments" 
          :key="index" 
          class="result-item department-item"
          @click="showDoctorsModal(dept)"
        >
          <view class="department-info">
            <view class="department-header">
              <text class="department-name">{{ dept.name }}</text>
              <text class="department-type">{{ dept.diseaseType || '通用' }}</text>
            </view>
            <view class="department-hospital">
              <text class="hospital-name">{{ dept.hospitalName }}</text>
            </view>
            <view class="department-snapshot">
              <text>{{ dept.snapshot || '暂无详细介绍' }}</text>
            </view>
          </view>
          <text class="iconfont icon-arrow-right arrow-right"></text>
        </view>

        <!-- 无结果提示 -->
        <view v-if="showNoResult" class="no-result">
          <text>暂无科室数据</text>
        </view>
      </view>
    </scroll-view>

    <!-- 医生列表弹窗 -->
    <uni-popup ref="doctorsPopup" type="bottom">
      <view class="doctors-modal">
        <view class="modal-header">
          <text class="modal-title">{{ currentDepartment.name }} - 医生列表</text>
        </view>
        <scroll-view class="modal-content" scroll-y>
          <view 
            v-for="(doctor, index) in doctors" 
            :key="index" 
            class="doctor-item"
            @click="navigateToDoctorDetail(doctor)"
          >
            <view class="doctor-avatar">
              <image :src="config.staticUrl + (doctor.imgUrl || '/static/images/default-avatar.png')" mode="aspectFill"></image>
            </view>
            <view class="doctor-info">
              <view class="doctor-name">{{ doctor.name }}</view>
              <view class="doctor-title">{{ doctor.jobTitle || '医师' }}</view>
              <view class="doctor-specialty">{{ doctor.professionalExpertise || '暂无专长介绍' }}</view>
            </view>
          </view>
          <view v-if="doctors.length === 0" class="no-doctors">
            暂无医生数据
          </view>
        </scroll-view>
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeDoctorsModal">取消</button>
        </view>
      </view>
    </uni-popup>

</template>

<script>
import { listDepartment, selectDepartmentByHospitalId } from '@/api/department'
import { selectDoctorByDepartmentId } from '@/api/doctor'
import { getToken } from '@/utils/auth'
import config from '@/config'

export default {
  data() {
    return {
      statusBarHeight: 20,
      departments: [],
      filteredDepartments: [],
      doctors: [],
      currentDepartment: {},
      config: config,
      loading: false,
      showNoResult: false,
      searchKeyword: '',
      isSearching: false
    }
  },
  created() {
    // 获取状态栏高度
    try {
      const windowInfo = uni.getWindowInfo()
      this.statusBarHeight = windowInfo.statusBarHeight
    } catch (error) {
      console.error('获取状态栏高度失败:', error)
      this.statusBarHeight = 20
    }
    
    // 检查登录状态
    if (!getToken()) {
      uni.showModal({
        title: '提示',
        content: '请先登录后再查看科室列表',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login/login'
            })
          } else {
            uni.navigateBack()
          }
        }
      })
      return
    }
    
    this.loadDepartments()
  },
  methods: {
    async loadDepartments() {
      this.loading = true
      this.showNoResult = false
      try {
        const res = await listDepartment({
          pageNum: 1,
          pageSize: 100
        })
        
        if (res.code === 200) {
          this.departments = res.rows || res.data || []
          this.filteredDepartments = [...this.departments]
          this.showNoResult = this.departments.length === 0
        } else {
          uni.showToast({
            title: res.msg || '获取科室列表失败',
            icon: 'none'
          })
          this.showNoResult = true
        }
      } catch (error) {
        console.error('获取科室列表失败:', error)
        uni.showToast({
          title: '获取科室列表失败',
          icon: 'none'
        })
        this.showNoResult = true
      } finally {
        this.loading = false
      }
    },
    
    // 搜索确认
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.cancelSearch()
        return
      }
      
      this.isSearching = true
      this.filterDepartments()
    },
    
    // 过滤科室
    filterDepartments() {
      const keyword = this.searchKeyword.toLowerCase()
      this.filteredDepartments = this.departments.filter(dept => 
        dept.name.toLowerCase().includes(keyword) || 
        (dept.hospitalName && dept.hospitalName.toLowerCase().includes(keyword)) ||
        (dept.diseaseType && dept.diseaseType.toLowerCase().includes(keyword))
      )
      this.showNoResult = this.filteredDepartments.length === 0
    },
    
    // 清除搜索
    clearSearch() {
      this.searchKeyword = ''
      if (this.isSearching) {
        this.cancelSearch()
      }
    },
    
    // 取消搜索（返回全部列表）
    cancelSearch() {
      this.searchKeyword = ''
      this.isSearching = false
      this.filteredDepartments = [...this.departments]
      this.showNoResult = this.departments.length === 0
    },
    
    // 输入变化时处理
    handleInputChange() {
      if (!this.searchKeyword.trim()) {
        this.cancelSearch()
      } else if (this.isSearching) {
        this.filterDepartments()
      }
    },
    
    async showDoctorsModal(department) {
      this.currentDepartment = department
      this.loading = true
      try {
        const res = await selectDoctorByDepartmentId(department.id)
        if (res.code === 200) {
          this.doctors = res.data || res.rows || []
          this.$refs.doctorsPopup.open()
        } else {
          uni.showToast({
            title: res.msg || '获取医生列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取医生列表失败:', error)
        uni.showToast({
          title: '获取医生列表失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    closeDoctorsModal() {
      this.$refs.doctorsPopup.close()
    },
    
    navigateToDoctorDetail(doctor) {
      this.closeDoctorsModal()
      uni.navigateTo({
        url: `/pages/medical/doctor-detail?id=${doctor.id}`,
        success: (res) => {
          res.eventChannel.emit('doctorData', {
            id: doctor.id,
            name: doctor.name,
            jobTitle: doctor.jobTitle,
            departmentName: doctor.departmentName,
            professionalExpertise: doctor.professionalExpertise,
            imgUrl: doctor.imgUrl
          })
        }
      })
    }
  }
}
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #F5F6FA;
}

/* 更新搜索栏样式 */
.search-box {
  position: fixed;
  left: 0;
  right: 0;
  height: 100rpx; /* 与参考样式一致的高度 */
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx 0; /* 与参考样式一致的padding */
  background-color: #FFFFFF; /* 白色背景 */
  margin-top: -45px;
  z-index: 10;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1); /* 添加阴影 */
}

.search-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.search-input {
  flex: 1;
  height: 70rpx; /* 与参考样式一致的高度 */
  background-color: #F5F6FA; /* 浅灰色背景 */
  border-radius: 35rpx; /* 较大的圆角 */
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.search-input input {
  flex: 1;
  height: 100%;
  font-size: 28rpx; /* 与参考样式一致的字体大小 */
  padding-left: 12rpx;
  background: transparent;
}

.cancel-btn {
  margin-left: 24rpx;
  font-size: 28rpx;
  color: #333; 
  white-space: nowrap;
}
/* 其余代码保持原有样式不变 */
.department-list {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #F5F6FA;
  margin-top: -50px;
    top: calc(var(--status-bar-height) + 110rpx);
}

.result-list {
  padding: 32rpx;
  padding-bottom: 32rpx;
}

.department-item {
  display: flex;
  align-items: center;
  padding: 32rpx;
  background-color: #FFFFFF;
  margin-bottom: 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(30, 144, 255, 0.1);
  transition: all 0.3s ease;
}

.department-item:active {
  transform: scale(0.98);
  background-color: #F5F6FA;
}

.department-info {
  flex: 1;
}

.department-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.department-name {
  font-size: 34rpx;
  color: #333333;
  font-weight: bold;
  margin-right: 16rpx;
}

.department-type {
  font-size: 24rpx;
  color: #1E90FF;
  background-color: rgba(30, 144, 255, 0.1);
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
}

.hospital-name {
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 12rpx;
}

.department-snapshot {
  font-size: 26rpx;
  color: #999999;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 1.5;
}

.arrow-right {
  color: #CCCCCC;
  font-size: 32rpx;
  margin-left: 20rpx;
}

.no-result {
  padding: 100rpx 0;
  text-align: center;
  color: #999999;
  font-size: 28rpx;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-icon {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #1E90FF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999999;
}

/* 医生弹窗样式 */
.doctors-modal {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 70vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
  text-align: center;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.modal-content {
  flex: 1;
  padding: 20rpx;
  max-height: 50vh;
}

.doctor-item {
  display: flex;
  padding: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
  align-items: center;
}

.doctor-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20rpx;
}

.doctor-avatar image {
  width: 100%;
  height: 100%;
}

.doctor-info {
  flex: 1;
}

.doctor-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.doctor-title {
  font-size: 26rpx;
  color: #1E90FF;
  margin-bottom: 8rpx;
}

.doctor-specialty {
  font-size: 24rpx;
  color: #999;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.no-doctors {
  padding: 40rpx;
  text-align: center;
  color: #999;
}

.modal-footer {
  padding: 20rpx;
  border-top: 1rpx solid #eee;
}

.cancel-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #f5f5f5;
  color: #666;
  border-radius: 40rpx;
  font-size: 30rpx;
}

.cancel-btn:active {
  background-color: #e5e5e5;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>